import React, { useEffect, useState } from "react";
import { Button, Space, Table, Modal, Form, Input } from "antd";
import type { FormProps } from "antd";
import type { TableProps } from "antd";
import api from "../../api/axios";
// 表格
interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}
//form表单
type FieldType = {
  title: string;
  content: string;
};
function Index() {
  //modal
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(1);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [title, setTitle] = useState<string>();
  //定义form需要区分数据回显
  const [form] = Form.useForm();
  //定一个一个标题区分是新增还是编辑
  const [add, setAdd] = useState("");
  //存储id
  const [editid, setEditid] = useState("");
  const getData = async (title: string) => {
    const res = await api.get("/article/list", {
      params: {
        page,
        pageSize,
        keyword: title,
      },
    });
    console.log(res);
    setList(res.data.rows);
    setTotal(res.data.count);
  };
  //modal弹框功能
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //新增
  const addlist = () => {
    setIsModalOpen(true);
    form.resetFields();
    setAdd(true);
  };
  //编辑
  const editlist = (record: any) => {
    setIsModalOpen(true);
    form.setFieldsValue(record);
    setEditid(record.id);
    setAdd(false);
  };
  //form表单新增编辑实现功能
  const onFinish: FormProps<FieldType>["onFinish"] = async (values) => {
    console.log("Success:", values);
    if (add) {
      try {
        const res = await api.post("/article", {
          ...values,
          authorId: 47529555,
        });
        getData();
        setIsModalOpen(false);
      } catch (error) {}
    } else {
      const res = await api.put(`/article/${editid}`, values);
      getData();
      setIsModalOpen(false);
    }
  };
  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };
  useEffect(() => {
    getData();
  }, []);
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "firstname",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "lastname",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "username",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button>删除</Button>
          <Button onClick={() => editlist(record)}>编辑</Button>
        </Space>
      ),
    },
  ];
  return (
    <div>
      <Button type="primary" onClick={() => addlist()}>
        新增内容
      </Button>
      <div>
        <Table<DataType> columns={columns} rowKey="id" dataSource={list} />
      </div>
      <div>
        {/* modal弹框 */}
        <Modal
          title={add ? "新增" : "编辑"}
          closable={{ "aria-label": "Custom Close Button" }}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Form
            form={form}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item<FieldType>
              label="lastname"
              name="title"
              rules={[
                { required: true, message: "Please input your username!" },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item<FieldType>
              label="username"
              name="content"
              rules={[
                { required: true, message: "Please input your password!" },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </div>
  );
}

export default Index;
